package org.example.ychdp.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

@Controller
public class CaptchaController {

    private static final int WIDTH = 120;      // 验证码图片宽度
    private static final int HEIGHT = 40;     // 验证码图片高度
    private static final int CODE_LENGTH = 4; // 验证码长度

    /**
     * 生成验证码图片并存储到 Session 中
     */
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response, HttpSession session) throws Exception {
        // 设置响应类型为图片
        response.setContentType("image/png");

        // 创建验证码图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        Random random = new Random();

        // 设置背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 验证码字符集
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder captchaCode = new StringBuilder();

        // 绘制随机字符
        g.setFont(new Font("Arial", Font.BOLD, 20));
        for (int i = 0; i < CODE_LENGTH; i++) {
            String ch = String.valueOf(chars.charAt(random.nextInt(chars.length())));
            captchaCode.append(ch);
            g.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150))); // 字体颜色
            g.drawString(ch, 20 * i + 10, 30); // 字符位置
        }

        // 添加干扰线
        for (int i = 0; i < 10; i++) {
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }

        // 将验证码存储到 Session 中
        session.setAttribute("captcha", captchaCode.toString());

        // 输出图片到响应流
        g.dispose();
        try (OutputStream os = response.getOutputStream()) {
            ImageIO.write(image, "png", os);
        }
    }

    /**
     * 验证用户输入的验证码
     */
    @GetMapping("/verifyCaptcha")
    @ResponseBody
    public String verifyCaptcha(String inputCode, HttpSession session) {
        String storedCaptcha = (String) session.getAttribute("captcha");
        if (storedCaptcha == null) {
            return "验证码已过期或不存在，请重新获取";
        }
        if (storedCaptcha.equalsIgnoreCase(inputCode)) {
            return "验证码正确";
        } else {
            return "验证码错误";
        }
    }
}
